<template>
  <div class="learn-container">
    <!-- 顶部导航 -->
    <div class="learn-header">
      <div class="header-left">
        <el-button @click="goBack" icon="ArrowLeft" text>返回课程</el-button>
        <div class="course-info">
          <h2>{{ course.title }}</h2>
          <span class="current-lesson">{{ currentLesson.title }}</span>
        </div>
      </div>
      <div class="header-right">
        <div class="progress-info">
          <span>学习进度: {{ learningProgress }}%</span>
          <el-progress :percentage="learningProgress" :show-text="false" :stroke-width="4" />
        </div>
        <el-button @click="toggleNotes" :type="showNotes ? 'primary' : ''" icon="EditPen">
          笔记
        </el-button>
        <el-button @click="toggleFullscreen" icon="FullScreen">全屏</el-button>
      </div>
    </div>

    <!-- 主要学习区域 -->
    <div class="learn-content" :class="{ 'fullscreen': isFullscreen }">
      <!-- 视频播放器 -->
      <div class="video-section" :class="{ 'with-sidebar': showSidebar }">
        <div class="video-container">
          <video
            ref="videoPlayer"
            :src="currentLesson.videoUrl"
            :poster="currentLesson.poster"
            controls
            @timeupdate="handleTimeUpdate"
            @ended="handleVideoEnd"
            @loadedmetadata="handleVideoLoaded"
            class="video-player"
          >
            您的浏览器不支持视频播放
          </video>
          
          <!-- 视频控制层 -->
          <div class="video-controls">
            <div class="controls-left">
              <el-button @click="togglePlay" :icon="isPlaying ? 'VideoPause' : 'VideoPlay'" circle />
              <span class="time-display">{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</span>
            </div>
            <div class="controls-center">
              <el-slider
                v-model="currentTime"
                :max="duration"
                :show-tooltip="false"
                @change="seekTo"
                class="progress-slider"
              />
            </div>
            <div class="controls-right">
              <el-button @click="changePlaybackRate" text>{{ playbackRate }}x</el-button>
              <el-button @click="toggleMute" :icon="isMuted ? 'Mute' : 'Microphone'" circle />
              <el-button @click="toggleFullscreen" icon="FullScreen" circle />
            </div>
          </div>
        </div>
        
        <!-- 课程资料 -->
        <div v-if="currentLesson.materials && currentLesson.materials.length" class="lesson-materials">
          <h4>课程资料</h4>
          <div class="materials-list">
            <div 
              v-for="material in currentLesson.materials" 
              :key="material.id"
              class="material-item"
            >
              <el-icon><Document /></el-icon>
              <span>{{ material.name }}</span>
              <el-button @click="downloadMaterial(material)" type="primary" link>下载</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 侧边栏 -->
      <div v-if="showSidebar" class="learn-sidebar">
        <el-tabs v-model="sidebarTab" class="sidebar-tabs">
          <!-- 课程目录 -->
          <el-tab-pane label="目录" name="chapters">
            <div class="chapters-list">
              <div 
                v-for="(chapter, chapterIndex) in chapters" 
                :key="chapter.id"
                class="chapter-item"
              >
                <div class="chapter-header" @click="toggleChapter(chapterIndex)">
                  <el-icon>
                    <CaretRight v-if="!chapter.expanded" />
                    <CaretBottom v-else />
                  </el-icon>
                  <span>第{{ chapterIndex + 1 }}章 {{ chapter.title }}</span>
                </div>
                
                <div v-show="chapter.expanded" class="lessons-list">
                  <div 
                    v-for="(lesson, lessonIndex) in chapter.lessons"
                    :key="lesson.id"
                    class="lesson-item"
                    :class="{ 'active': lesson.id === currentLesson.id, 'completed': lesson.completed }"
                    @click="switchLesson(lesson)"
                  >
                    <div class="lesson-info">
                      <el-icon>
                        <CircleCheckFilled v-if="lesson.completed" class="completed-icon" />
                        <VideoPlay v-else-if="lesson.type === 'video'" />
                        <Document v-else />
                      </el-icon>
                      <span class="lesson-title">{{ lessonIndex + 1 }}. {{ lesson.title }}</span>
                    </div>
                    <span class="lesson-duration">{{ lesson.duration }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <!-- 学习笔记 -->
          <el-tab-pane label="笔记" name="notes" v-if="showNotes">
            <div class="notes-section">
              <div class="notes-header">
                <el-button @click="addNote" type="primary" size="small" icon="Plus">添加笔记</el-button>
              </div>
              
              <div class="notes-list">
                <div 
                  v-for="note in notes" 
                  :key="note.id"
                  class="note-item"
                >
                  <div class="note-header">
                    <span class="note-time">{{ formatTime(note.timestamp) }}</span>
                    <el-button @click="editNote(note)" type="primary" link size="small">编辑</el-button>
                    <el-button @click="deleteNote(note.id)" type="danger" link size="small">删除</el-button>
                  </div>
                  <div class="note-content">{{ note.content }}</div>
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 底部导航 -->
    <div class="learn-footer">
      <div class="footer-left">
        <el-button 
          @click="previousLesson" 
          :disabled="!hasPreviousLesson"
          icon="ArrowLeft"
        >
          上一节
        </el-button>
      </div>
      
      <div class="footer-center">
        <el-button @click="toggleSidebar" :type="showSidebar ? 'primary' : ''" icon="Menu">
          {{ showSidebar ? '隐藏' : '显示' }}目录
        </el-button>
      </div>
      
      <div class="footer-right">
        <el-button 
          @click="nextLesson" 
          :disabled="!hasNextLesson"
          type="primary"
        >
          下一节
          <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 添加笔记对话框 -->
    <el-dialog v-model="noteDialogVisible" title="添加笔记" width="500px">
      <el-form :model="noteForm" label-width="80px">
        <el-form-item label="时间点">
          <el-input v-model="noteForm.timestamp" disabled />
        </el-form-item>
        <el-form-item label="笔记内容">
          <el-input 
            v-model="noteForm.content" 
            type="textarea" 
            :rows="4"
            placeholder="请输入笔记内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="noteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNote">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getCourseDetail, 
  getCourseChapters, 
  getLessonDetail,
  updateLessonProgress,
  completeLesson,
  getCourseNotes,
  addCourseNote,
  updateCourseNote,
  deleteCourseNote
} from '@/api/classroom'

const route = useRoute()
const router = useRouter()

const videoPlayer = ref(null)
const loading = ref(true)
const isFullscreen = ref(false)
const showSidebar = ref(true)
const showNotes = ref(false)
const sidebarTab = ref('chapters')
const noteDialogVisible = ref(false)

const course = ref({})
const chapters = ref([])
const currentLesson = ref({})
const notes = ref([])

// 视频播放状态
const isPlaying = ref(false)
const currentTime = ref(0)
const duration = ref(0)
const playbackRate = ref(1)
const isMuted = ref(false)
const learningProgress = ref(0)

// 笔记表单
const noteForm = reactive({
  timestamp: '',
  content: ''
})

// 计算属性
const hasPreviousLesson = computed(() => {
  // 实现获取上一节课的逻辑
  return true
})

const hasNextLesson = computed(() => {
  // 实现获取下一节课的逻辑
  return true
})

// 获取课程信息
const getCourseInfo = async () => {
  loading.value = true
  try {
    const courseId = route.params.id
    const [courseRes, chaptersRes] = await Promise.all([
      getCourseDetail(courseId),
      getCourseChapters(courseId)
    ])
    
    if (courseRes.code === 200) {
      course.value = courseRes.data
    }
    
    if (chaptersRes.code === 200) {
      chapters.value = chaptersRes.data.map(chapter => ({
        ...chapter,
        expanded: true
      }))
      
      // 设置当前课时（第一个未完成的课时）
      if (chapters.value.length > 0) {
        const firstChapter = chapters.value[0]
        if (firstChapter.lessons && firstChapter.lessons.length > 0) {
          currentLesson.value = firstChapter.lessons[0]
          loadLesson(currentLesson.value.id)
        }
      }
    }
  } catch (error) {
    console.error('获取课程信息失败:', error)
    ElMessage.error('获取课程信息失败')
  } finally {
    loading.value = false
  }
}

// 加载课时详情
const loadLesson = async (lessonId) => {
  try {
    const response = await getLessonDetail(lessonId)
    if (response.code === 200) {
      currentLesson.value = response.data
      loadNotes()
    }
  } catch (error) {
    console.error('获取课时详情失败:', error)
  }
}

// 加载笔记
const loadNotes = async () => {
  try {
    const response = await getCourseNotes(route.params.id, { lessonId: currentLesson.value.id })
    if (response.code === 200) {
      notes.value = response.data.records || []
    }
  } catch (error) {
    console.error('获取笔记失败:', error)
  }
}

// 视频事件处理
const handleTimeUpdate = () => {
  if (videoPlayer.value) {
    currentTime.value = videoPlayer.value.currentTime
    
    // 更新学习进度
    const progress = (currentTime.value / duration.value) * 100
    updateProgress(progress)
  }
}

const handleVideoEnd = () => {
  // 视频播放结束，标记为完成
  completeCurrentLesson()
}

const handleVideoLoaded = () => {
  if (videoPlayer.value) {
    duration.value = videoPlayer.value.duration
  }
}

// 更新学习进度
const updateProgress = async (progress) => {
  try {
    await updateLessonProgress(currentLesson.value.id, progress, currentTime.value)
  } catch (error) {
    console.error('更新进度失败:', error)
  }
}

// 完成当前课时
const completeCurrentLesson = async () => {
  try {
    await completeLesson(currentLesson.value.id, duration.value)
    currentLesson.value.completed = true
    ElMessage.success('课时学习完成！')
  } catch (error) {
    console.error('完成课时失败:', error)
  }
}

// 视频控制
const togglePlay = () => {
  if (videoPlayer.value) {
    if (isPlaying.value) {
      videoPlayer.value.pause()
    } else {
      videoPlayer.value.play()
    }
    isPlaying.value = !isPlaying.value
  }
}

const seekTo = (time) => {
  if (videoPlayer.value) {
    videoPlayer.value.currentTime = time
  }
}

const changePlaybackRate = () => {
  const rates = [0.5, 0.75, 1, 1.25, 1.5, 2]
  const currentIndex = rates.indexOf(playbackRate.value)
  const nextIndex = (currentIndex + 1) % rates.length
  playbackRate.value = rates[nextIndex]
  
  if (videoPlayer.value) {
    videoPlayer.value.playbackRate = playbackRate.value
  }
}

const toggleMute = () => {
  if (videoPlayer.value) {
    videoPlayer.value.muted = !videoPlayer.value.muted
    isMuted.value = videoPlayer.value.muted
  }
}

const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
    isFullscreen.value = true
  } else {
    document.exitFullscreen()
    isFullscreen.value = false
  }
}

// 课程导航
const switchLesson = (lesson) => {
  currentLesson.value = lesson
  loadLesson(lesson.id)
}

const previousLesson = () => {
  // 实现切换到上一节课的逻辑
}

const nextLesson = () => {
  // 实现切换到下一节课的逻辑
}

const toggleChapter = (index) => {
  chapters.value[index].expanded = !chapters.value[index].expanded
}

const toggleSidebar = () => {
  showSidebar.value = !showSidebar.value
}

const toggleNotes = () => {
  showNotes.value = !showNotes.value
  if (showNotes.value) {
    sidebarTab.value = 'notes'
  }
}

// 笔记管理
const addNote = () => {
  noteForm.timestamp = formatTime(currentTime.value)
  noteForm.content = ''
  noteDialogVisible.value = true
}

const editNote = (note) => {
  noteForm.timestamp = formatTime(note.timestamp)
  noteForm.content = note.content
  noteForm.id = note.id
  noteDialogVisible.value = true
}

const saveNote = async () => {
  try {
    const noteData = {
      lessonId: currentLesson.value.id,
      courseId: route.params.id,
      timestamp: currentTime.value,
      content: noteForm.content
    }
    
    if (noteForm.id) {
      await updateCourseNote(noteForm.id, noteData)
      ElMessage.success('笔记更新成功')
    } else {
      await addCourseNote(noteData)
      ElMessage.success('笔记添加成功')
    }
    
    noteDialogVisible.value = false
    loadNotes()
  } catch (error) {
    console.error('保存笔记失败:', error)
    ElMessage.error('保存笔记失败')
  }
}

const deleteNote = async (noteId) => {
  try {
    await deleteCourseNote(noteId)
    ElMessage.success('笔记删除成功')
    loadNotes()
  } catch (error) {
    console.error('删除笔记失败:', error)
    ElMessage.error('删除笔记失败')
  }
}

// 工具函数
const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`
}

const downloadMaterial = (material) => {
  // 实现下载课程资料的逻辑
  window.open(material.url, '_blank')
}

const goBack = () => {
  router.push(`/classroom/course/${route.params.id}`)
}

// 键盘快捷键
const handleKeydown = (event) => {
  if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
    return
  }
  
  switch (event.code) {
    case 'Space':
      event.preventDefault()
      togglePlay()
      break
    case 'ArrowLeft':
      event.preventDefault()
      seekTo(Math.max(0, currentTime.value - 10))
      break
    case 'ArrowRight':
      event.preventDefault()
      seekTo(Math.min(duration.value, currentTime.value + 10))
      break
    case 'KeyF':
      event.preventDefault()
      toggleFullscreen()
      break
  }
}

onMounted(() => {
  getCourseInfo()
  document.addEventListener('keydown', handleKeydown)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style lang="scss" scoped>
.learn-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #000;
  color: white;
}

.learn-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: rgba(0, 0, 0, 0.8);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.course-info {
  h2 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 4px;
  }
  
  .current-lesson {
    font-size: 14px;
    color: rgba(255, 255, 255, 0.7);
  }
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.progress-info {
  display: flex;
  align-items: center;
  gap: 12px;
  
  span {
    font-size: 14px;
    white-space: nowrap;
  }
  
  .el-progress {
    width: 100px;
  }
}

.learn-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  
  &.fullscreen {
    .video-section {
      width: 100% !important;
    }
    
    .learn-sidebar {
      display: none;
    }
  }
}

.video-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  
  &.with-sidebar {
    width: calc(100% - 350px);
  }
}

.video-container {
  position: relative;
  flex: 1;
  background: #000;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.video-controls {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  opacity: 0;
  transition: opacity 0.3s ease;
  
  .video-container:hover & {
    opacity: 1;
  }
}

.controls-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.controls-center {
  flex: 1;
}

.controls-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.time-display {
  font-size: 14px;
  color: white;
  min-width: 100px;
}

.progress-slider {
  :deep(.el-slider__runway) {
    background: rgba(255, 255, 255, 0.3);
  }
  
  :deep(.el-slider__bar) {
    background: var(--el-color-primary);
  }
}

.lesson-materials {
  padding: 20px;
  background: rgba(255, 255, 255, 0.05);
  
  h4 {
    margin-bottom: 16px;
    font-size: 16px;
  }
}

.materials-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.material-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
}

.learn-sidebar {
  width: 350px;
  background: rgba(255, 255, 255, 0.05);
  border-left: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  flex-direction: column;
}

.sidebar-tabs {
  flex: 1;
  
  :deep(.el-tabs__header) {
    margin: 0;
    background: rgba(255, 255, 255, 0.05);
  }
  
  :deep(.el-tabs__nav-wrap) {
    padding: 0 20px;
  }
  
  :deep(.el-tabs__content) {
    flex: 1;
    overflow: auto;
  }
}

.chapters-list {
  padding: 20px;
}

.chapter-item {
  margin-bottom: 16px;
}

.chapter-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  cursor: pointer;
  font-weight: 600;
  
  &:hover {
    color: var(--el-color-primary);
  }
}

.lessons-list {
  margin-left: 20px;
  margin-top: 8px;
}

.lesson-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 4px;
  
  &:hover {
    background: rgba(255, 255, 255, 0.1);
  }
  
  &.active {
    background: var(--el-color-primary);
    color: white;
  }
  
  &.completed {
    .lesson-title {
      text-decoration: line-through;
      opacity: 0.7;
    }
  }
}

.lesson-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.lesson-title {
  font-size: 14px;
}

.lesson-duration {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.completed-icon {
  color: var(--el-color-success);
}

.notes-section {
  padding: 20px;
}

.notes-header {
  margin-bottom: 16px;
}

.note-item {
  padding: 12px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  margin-bottom: 12px;
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.note-time {
  font-size: 12px;
  color: var(--el-color-primary);
}

.note-content {
  font-size: 14px;
  line-height: 1.5;
}

.learn-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: rgba(0, 0, 0, 0.8);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}
</style>
